package com.yitongmao.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.yitongmao.AppConstancts;
import com.yitongmao.bean.AddressBean;
import com.yitongmao.bean.LoginHuancunBean;
import com.yitongmao.bottompop.Area;
import com.yitongmao.bottompop.CityPicker;
import com.yitongmao.bottompop.CityUtil2;
import com.yitongmao.bottompop.FileUtil;
import com.yitongmao.bottompop.PopupWindowUtil;
import com.yitongmao.bottompop.SharedConfig;
import com.yitongmao.bottompop.SpKey;
import com.yitongmao.bottompop.ThreadUtils;
import com.yitongmao.bottompop.UIUtils;
import com.yitongmao.common.CallBackListener;
import com.yitongmao.core.cache.ACache;
import com.yitongmao.core.network.service.BaseService;
import com.yitongmao.util.SignUtil;
import com.yitongmao.util.ToastUtils;
import com.yitongmao.yitmfruit.R;
import com.zhy.autolayout.AutoLinearLayout;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SetAddAddressActivity extends AppCompatActivity implements View.OnClickListener {
    private AutoLinearLayout mReceivingAddress;
    private EditText nick_name;
    private EditText user_phone;
    private EditText mMinuteAddress;
    private SharedPreferences sp;
    private AutoLinearLayout ziliao;
    private CityPicker fragmentCityPicker;
    private String dq;
    private TextView fragment_area;
    private ImageView mAddressmoren;
    private boolean flag = true;
    private Button mSaveAddress;
    private String citycode;
    private String countryCode;
    private String provicecode;
    private String status = "00";
    private String name;
    private String phone;
    private String address;
    private LoginHuancunBean loginHuancunBean;
    private String userId;
    private int loginId1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_add_address);
        ThreadUtils.runOnBackThread(new Runnable() {
            @Override
            public void run() {
                //初始化城市数据
                String area_str;
                if (sp == null)
                    sp = new SharedConfig(UIUtils.getContext()).getCommoneSp();
                String str = sp.getString(SpKey.AAASSEST2, "");
                if (!TextUtils.isEmpty(str))
                    area_str = str;
                else {
                    area_str = FileUtil.readAssets(UIUtils.getContext(), "a2.json");
                    sp.edit().putString(SpKey.AAASSEST2, area_str).commit();
                }
                Gson gson = new Gson();
                Area area = gson.fromJson(area_str, Area.class);
                CityUtil2 cityUtil2 = new CityUtil2(area);
                cityUtil2.initProvince();
                cityUtil2.initCity();
                cityUtil2.initCountry();
            }
        });
        initView();
        setOnClick();
    }

    private void setOnClick() {
        //点击弹框
        mReceivingAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fishKey();
                View shanghu = PopupWindowUtil.toogleInButton(SetAddAddressActivity.this, SpKey.DQ, ziliao, R.layout.fragment_area);
                setPopupListener(shanghu);
            }
        });
        //点击设置默认地址
        mAddressmoren.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (flag) {
                    status = "01";
                    mAddressmoren.setImageResource(R.drawable.dizhixuanzhong);
                    flag = false;
                } else {
                    mAddressmoren.setImageResource(R.drawable.dizhimeixuanzhong);
                    status = "00";
                    flag = true;
                }
            }
        });

    }

    public void fishKey() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(user_phone.getWindowToken(), 0);
        }
    }

    public void setPopupListener(View view) {
        fragmentCityPicker = (CityPicker) view.findViewById(R.id.fragment_cityPicker);
        Button fragment_area_confirm = (Button) view.findViewById(R.id.fragment_area_confirm);
        fragment_area_confirm.setOnClickListener(this);
    }

    private void initView() {
        Gson gson = new Gson();
        String loginId = ACache.get(SetAddAddressActivity.this).getAsString("loginId");
        if (loginId != null) {
            loginHuancunBean = gson.fromJson(loginId, LoginHuancunBean.class);
            int id = loginHuancunBean.userInfo.id;
            loginId1 = loginHuancunBean.userInfo.loginId;
            userId = String.valueOf(id);
        }
        fragment_area = (TextView) findViewById(R.id.fragment_area);
        ziliao = (AutoLinearLayout) findViewById(R.id.ziliao);
        //姓名
        nick_name = (EditText) findViewById(R.id.nick_name11);
        //禁止输入空格  和特殊符号
        setEditTextInhibitInputSpace(nick_name);
        setEditTextInhibitInputSpeChat(nick_name);
        //手机号
        user_phone = (EditText) findViewById(R.id.user_phone);
        //详细地址
        mMinuteAddress = (EditText) findViewById(R.id.mMinuteAddress);
        mAddressmoren = (ImageView) findViewById(R.id.mAddressmoren);//设置默认地址
        mReceivingAddress = (AutoLinearLayout) findViewById(R.id.mReceivingAddress);
        //保存收获地址
        mSaveAddress = (Button) findViewById(R.id.mSaveAddress);
        //保存收货地址
        mSaveAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                name = nick_name.getText().toString().trim();
                phone = user_phone.getText().toString().trim();
                address = mMinuteAddress.getText().toString().trim();
                saveAddress(provicecode, citycode, countryCode, name, phone, address, userId, status);
            }
        });

    }
    //禁止输入空格
    public static void setEditTextInhibitInputSpace(EditText editText) {
        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if (source.equals(" "))return "";
                else return null;
            }
        };
        editText.setFilters(new InputFilter[]{filter});
    }
    //禁止输入特殊符号
    public static void setEditTextInhibitInputSpeChat(EditText editText){
        InputFilter filter=new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                String speChat="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
                Pattern pattern = Pattern.compile(speChat);
                Matcher matcher = pattern.matcher(source.toString());
                if(matcher.find())return "";
                else return null;
            }
        };
        editText.setFilters(new InputFilter[]{filter});
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fragment_area_confirm:
                String citys = fragmentCityPicker.getCity_string();
                provicecode = fragmentCityPicker.getProvicecode();
                citycode = fragmentCityPicker.getCitycode();
                countryCode = fragmentCityPicker.getCountryCode();
                String[] strings = citys.split("#");
                dq = "";
                for (String str : strings) {
                    dq = dq + str;
                }
                fragment_area.setText(dq);
                PopupWindowUtil.cancel(SpKey.DQ);
                break;
        }
    }

    public void saveAddress(String provinceId, String cityId, String countryId, final String name, final String phone, final String address, String userId, final String status) {

        Map params = new TreeMap();
        String timestamp = String.valueOf(System.currentTimeMillis());
        String nonce = String.valueOf(new Random().nextInt());
        params.put("provinceId", provinceId);
        params.put("cityId", cityId);
        params.put("countryId", countryId);
        params.put("name", name);
        params.put("phone", phone);
        params.put("address", address);
        params.put("userId", userId);
        params.put("status", status);
        params.put("timestamp", timestamp);
        params.put("signLogin",SignUtil.signLogin(nonce,timestamp));
        params.put("loginId",String.valueOf(loginId1));
        params.put("nonce", nonce);
        params.put("sign", SignUtil.sign(params)); //这里也需要时完整的url
        BaseService.getInstance().simplePostRequest(AppConstancts.Net.saveAddressUrl, params, new CallBackListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(Object result) {
                String string = (String) result;
                Log.e("Gson", "" + string);
                Gson gson = new Gson();
                AddressBean addressBean = gson.fromJson(string, AddressBean.class);
                if (addressBean.result.state.equals("1")) {
                    ToastUtils.showShort(SetAddAddressActivity.this, "" + addressBean.result.message);
                    Intent intent = new Intent(SetAddAddressActivity.this, AddAddressActivity.class);
                    startActivity(intent);
                    finish();
                }
            }
            @Override
            public void onFail(Object result) {
              /*  Log.e("zzz", "provicecode:" + provicecode);//省
                Log.e("zzz", "citycode:" + citycode);//市
                Log.e("zzz", "name:" + name);//区
                Log.e("zzz", "phone:" + phone);//区
                Log.e("zzz", "address:" + address);//区
                Log.e("zzz", "status:" + status);//区
                Log.e("zzz", "userId:" + userID);//区
                Log.e("zzz", "失败：" + AppConstancts.Net.saveAddressUrl);
                Log.e("zzz", "失败：" + result);*/
                ToastUtils.showShort(SetAddAddressActivity.this, "失败");
            }
        });
    }
}
